<?php

namespace app\web\controller;

use app\web\model\CartModel;
use think\Controller;
use think\Request;
use think\Db;

class CartController extends Controller
{
    // 跳订单
    public function index()
    {
        $res = model('CartModel') ->cartmess();
        // var_dump($res);die;
        if($res !== false){
            for($k=0; $k<count($res); $k++){
                $res[$k]['goods_Mprice'] = $res[$k]['count']*$res[$k]['price'];
            }

            $res[0]['Allprice'] = 0;
            // var_dump($res);die;
            
            for($i=0; $i<(count($res)); $i++){
                $res[0]['Allprice'] += $res[$i]['goods_Mprice'];
            }
        }else{
            $res = false;
        }
            return view('cart/checkout',['res'=>$res]);
    }

    public function cart($id)
    {
        
        $data = Db::table('goods') ->field('name, price') ->where('id',$id) ->find();
        $data['tableid'] = '36';
        $data['id'] = $data['tableid'];
        $data['goodsid'] = $id;
        // var_dump($data);die;
        $data['goodsname'] = $data['name'];
        unset($data['name']);

        $res = Db::table('cart')-> field('count')->where(['goodsid'=>$id, 'tableid'=>$data['tableid']]) ->find();

        if (empty($res)) {
            $data['count'] = 1;
            $result = Db::table('cart')->insert($data);
        }else{
            $count['count'] = $res['count'] + 1;
            $result = Db::table('cart') ->where(['goodsid'=>$id, 'tableid'=>$data['tableid']]) ->update($count);
        }

        if ($result > 0) {
            $info['status'] = true;
            $info['id'] = $id;
            $info['info'] = '添加成功!';
        } else {
            $info['status'] = false;
            $info['id'] = $id;
            $info['info'] = '添加失败!';
        }
        // JSON 返回
        return json($info);
    }

    public function delcart($id)
    {
        $tableid = '36';
        $data = Db::table('cart') ->where('tableid',$tableid) ->select();
        for ($jj=0; $jj<count($data); $jj++) {
            $data = Db::table('cart') ->where('tableid',$tableid) ->delete($data[$jj]);
        }

        if ($data > 0) {
            $info['status'] = true;
            $info['id'] = $id;
            $info['info'] = '删除成功!';
        } else {
            $info['status'] = false;
            $info['id'] = $id;
            $info['info'] = '删除失败!';
        }
        // JSON 返回
        return json($info);
    }

}













